package com.kfm.mapper;

import com.kfm.builder.AccountSQLBuilder;
import com.kfm.model.Account;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;


@CacheNamespace(size = 512)
public interface IAccountMapper {


    @Select("select * from account")
    @ResultMap("myResult")
    List<Account> selectAll();

    @Select("select id, user_id, money from account where id = #{id}")
    @Results(id = "myResult", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "money", property = "money")
    })
    Account selectById(Integer id);

    @Insert("insert into account (user_id, money) values(#{userId}, #{money})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    int insert(Account account);



    @Select("select a.*, su.id uid, su.username, su.password from account a left join sys_user su on su.id = a.user_id where a.id = #{id}")
    @Results(id = "resultWithSysUser", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "money", property = "money"),
            @Result(property = "sysUser", one = @One(resultMap = "com.kfm.mapper.ISysUserMapper.sysUserResult"))
    })
    Account selectByIdWithSysUser(Integer id);


    @Select("select * from account where id = #{id}")
    @Results(id = "resultWithSysUser2", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "money", property = "money"),
            @Result(property = "sysUser", column = "user_id", one = @One(select = "com.kfm.mapper.ISysUserMapper.selectById", fetchType = FetchType.LAZY))
        })
    Account selectByIdWithSysUser2(Integer id);


    @Select("select * from account where user_id = #{userId}")
    @ResultMap("myResult")
    List<Account> selectByUserId(String userId);


    // sql 语句中要包含在 <script> 中才可以使用 动态 sql 标签
    @Update({
            "<script>",
            "update account",
            "<set>",
            "<if test='userId != null'> user_id = #{userId}, </if>",
            "<if test='money != null'> money = #{money}, </if>",
            "</set>",
            "where id = #{id}",
            "</script>"
    })
    int updateById(Account account);


    @SelectProvider(type = AccountSQLBuilder.class, method = "selectAll")
    List<Account> selectAll2(Account account);


    @UpdateProvider(type = AccountSQLBuilder.class, method = "update")
    int update2(Account account);


    @InsertProvider(type = AccountSQLBuilder.class, method = "insert")
    int insert2(Account account);

}
